﻿using Sunny.UI;
using System.Windows.Forms;
using System;
using CoreShop.Model;
using System.Collections.Generic;
using CoreShop.Library;
using CoreShop.PrintService;
using CoreShop.Services;
using System.Threading;
using CoreShop.App.Test;
using CoreShop.Model.FromBody;
using System.IO.Pipes;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Runtime.InteropServices;
using Sunny.UI.Win32;
using System.Xml;
using Microsoft.AspNetCore.SignalR.Client;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO.Ports;
using CoreShop.App.Units.Interface;

namespace CoreShop.App
{
    public partial class FNavigation : UIPage
    {
        //public FOrdering frmOrdering = null;
        //public frmDeskMain frmTables = null;

        private HubConnection conn1 { get; set; }
        static System.Timers.Timer timer_conn = null;
        private int iTime_conn = 0;

        public FNavigation()
        {
            InitializeComponent();
        }

        private void btnOrdering_Click(object sender, System.EventArgs e)
        {            
            Program.frmMainWin.ShowOrdering(0);
        }

        private void FNavigation_Load(object sender, System.EventArgs e)
        {
            //读取配置版本号
            string updateListXml = Application.StartupPath + "\\UpdateListEx.xml";
            XmlFiles serverXmlFiles = new XmlFiles(updateListXml);
            XmlNodeList newNodeList = serverXmlFiles.GetNodeList("AutoUpdater/Files");//5+1+a+s+p+x
            var appVersion = newNodeList.Item(0).Attributes["Ver"].Value.Trim(); ;
            pnlMain.Visible = false;
            this.lbl_msg1.Visible = false;
            this.userInfo.Text = string.Format("门店：{0}   登录用户：{1}   {2}",AppConstVars.sysStore.storeName,AppConstVars.sysUser.userName, AppConstVars.sPosVersion);
            //this.ShowFullScreen = AppConstVars.showFullScreen;

            //ShowStatusForm(10, "程序加载中，请稍后......", 0);
            try
            {                
                //SystemEx.Delay(50);
                //SetStatusFormDescription("程序加载中(" + 100 + "%)......");                

                //CreateCustDisplay();

                CustomerDisplay.SetLedPara();//设置顾显
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "错误号：FNavigation");
            }
            finally
            {
                //HideStatusForm();
                pnlMain.Visible = true;
            }
        }

        private void btnSoldout_Click(object sender, EventArgs e)
        {
            var frm = new frmFoodSoldoutList();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnOrderList_Click(object sender, EventArgs e)
        {
            Program.frmMainWin.SetOrderList();
        }

        private void btnMember_Click(object sender, EventArgs e)
        {
            Program.frmMainWin.ShowMember();
        }

        private void uiHeaderButton1_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isSysSetup, 0)) return;
            var frm = new frmPrintTemplate();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnFoodPrintSet_Click(object sender, EventArgs e)
        {

        }

        private void btnSetup_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isSysSetup, 0)) return;
            var frm = new frmSystemSetup();
            frm.ShowDialog();
            frm.Dispose();
        }


        private void uiHeaderButton5_Click_1(object sender, EventArgs e)
        {
            var frm = new FKeyBoard();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnOffClass_Click(object sender, EventArgs e)
        {
            Program.frmMainWin.SetOffClass();
        }

        private void btnOnClass_Click(object sender, EventArgs e)
        {
            var frm = new frmClassOn();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
           Program.frmMainWin.SetMainwinClose();
        }

        private void btnReports_Click(object sender, EventArgs e)
        {
            Program.frmMainWin.ShowReports();
        }

        public void CloseComport()
        {
            try
            {
                // 停止接收数据
                Program.frmMainWin.comport.DataReceived -= Program.frmMainWin.port_DataReceived; 

                // 等待当前的数据接收事件处理完成
                if (Program.frmMainWin._dataReceivedEvent.WaitOne(1000)) // 等待1秒
                {
                    if (Program.frmMainWin.comport.IsOpen)
                    {
                        // 先禁用事件，再关闭串口
                        Program.frmMainWin.comport.DtrEnable = false;
                        Program.frmMainWin.comport.RtsEnable = false;

                        // 在后台线程中关闭串口
                        ThreadPool.QueueUserWorkItem(_ =>
                        {
                            try
                            {
                                Program.frmMainWin.comport.Close();
                            }
                            catch (Exception ex)
                            {
                                //if (ErrorReceived != null)
                                //{
                                //    ErrorReceived(this, new SerialErrorEventArgs(ex));
                                //}
                            }
                        });
                    }
                }
                else
                {
                    // 超时处理
                    //if (ErrorReceived != null)
                    //{
                    //    ErrorReceived(this, new SerialErrorEventArgs(new TimeoutException("关闭串口时超时")));
                    //}
                }
            }
            catch (Exception ex)
            {
                //if (ErrorReceived != null)
                //{
                //    ErrorReceived(this, new SerialErrorEventArgs(ex));
                //}
            }
        }

        private void FNavigation_FormClosed(object sender, FormClosedEventArgs e)
        {
            if ((Program.frmMainWin.comport != null) && (Program.frmMainWin.comport.IsOpen))
            {
                //Program.frmMainWin.comport.DataReceived -= Program.frmMainWin.port_DataReceived;
                //Program.frmMainWin.comport.DiscardInBuffer();
                //Program.frmMainWin.comport.Close();
                CloseComport();
            }
            if ((CustomerDisplay.serialPort != null) && (CustomerDisplay.serialPort.IsOpen))
            {
                CustomerDisplay.serialPort.DiscardInBuffer();
                CustomerDisplay.serialPort.Close();
            }
        }

        private void btnDepositary_Click(object sender, EventArgs e)
        {
            var uIDepositary = new UIDepositary();
            UIToolStripDropDown DeskOperate = new UIToolStripDropDown(uIDepositary);
            DeskOperate.ValueChanged += Depositary_ValueChanged;
            DeskOperate.Show(btnDepositary, 0, 0);
        }

        private void Depositary_ValueChanged(object sender, object value)
        {
            if (CommFunc.ConvertToInt32(value) == 1)
            {
                var frm = new frmSelectFoods((int)Library.GlobalEnumVars.BillType.TempStorage, "物品寄存录入");
                frm.ShowDialog();
                frm.Dispose();
            }
            else if (CommFunc.ConvertToInt32(value) == 2)
            {

            }
            else if (CommFunc.ConvertToInt32(value) == 3)
            {

            }
        }
                
        private async void btn_CheckConn(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(conn1.ConnectionId))
                {
                    await SetLinkToHost();
                    return;
                }
                var state = conn1.State.ToString();
                if (state != "Connected")
                {
                    await SetLinkToHost();
                }
                //var ret = await conn1.InvokeAsync<string>("CallByClientWithReturnValue", $"{txt_senMsg.Text}");
                //txt_receive.Text = ret;
            }
            catch (Exception ex)
            {
                 
            }
        }

        private void Timer_Conn(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                timer_conn.Enabled = false;
                iTime_conn = iTime_conn + 1;

                if (iTime_conn % 10 == 0)
                {
                    btn_CheckConn(null, null);
                }

                if (iTime_conn % 60 == 0)
                {
                    CheckConnFromSevice();
                    iTime_conn = 0;
                }

            }
            catch { }
            finally
            {
                timer_conn.Enabled = true;
            }
        }


        private async Task<bool> SetLinkToHost()
        {
            try
            {
                if (conn1 != null)
                {
                    //await conn1.StopAsync();
                    conn1.DisposeAsync();
                }
                conn1 = null;
                conn1 = SignaRlHelp.GetConnection(AppConstVars.sysStore.channel.ToString());
                await conn1.StartAsync();
                //被服务器端调用
                conn1.On<string>("CallByServer", (string msg) =>
                {
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        try
                        {
                            SetReceiveMessage(msg);
                        }
                        catch (Exception)
                        {
                        }
                    }));
                });

 
                SignalRUser user = new SignalRUser();
                user.connectionId = conn1.ConnectionId;
                user.storeId = AppConstVars.sysStore.id.ToString();
                ClientMessage message = new ClientMessage();
                message.type = "userInfo";
                message.content = JsonConvert.SerializeObject(user);
                //连接成功后通知服务端写入用户信息
                await conn1.InvokeAsync<string>("CallByClient", $"{JsonConvert.SerializeObject(message)}");
 
                return true;
            }
            catch (Exception ex)
            {
 
                return false;
            }
        }


        private void SetReceiveMessage(string json)
        {
            try
            {
                var frombody = JsonConvert.DeserializeObject<FromBodyModel>(json);
                var msgLog = "【" + EnumHelper.GetDescByValue<GlobalEnumVars.MessageCode>(frombody.code) + "】" + json;
                var bl = SignalClientServices.ReceiveMessage(frombody);
                if (bl) msgLog += "【成功】";
                else msgLog += "【失败】";
 
            }
            catch
            {
            }
        }

        /// <summary>
        /// 检查客户端和服务端的连接情况
        /// </summary>
        private async void CheckConnFromSevice()
        {
            bool bLinkFlag = false;
            try
            {
                if (string.IsNullOrEmpty(conn1.ConnectionId))
                {
                    await SetLinkToHost();
                    return;
                }
                SignalRUser user = new SignalRUser();
                user.connectionId = conn1.ConnectionId;
                user.storeId = AppConstVars.sysStore.id.ToString();
                ClientMessage message = new ClientMessage();
                message.type = "userInfo";
                message.content = JsonConvert.SerializeObject(user);
                //连接成功后通知服务端写入用户信息
                bLinkFlag = true;
                var ret = await conn1.InvokeAsync<string>("CallByClientReturn", $"{JsonConvert.SerializeObject(message)}");
                bLinkFlag = false;
                //txt_receive.Text = ret;
            }
            catch (Exception ex)
            {
 
                bLinkFlag = true;
                //txt_receive.Text = ex.Message;
            }
            if (bLinkFlag)
            {
                await SetLinkToHost();
                return;
            }
        }

        private void btnGoodsList_Click(object sender, EventArgs e)
        {
            //var frm = new frmFoodSelect(null);
            //if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
            //}
            //frm.Dispose();
            Program.frmMainWin.ShowGoodsList();
        }

        private void btnDataMonitor_Click(object sender, EventArgs e)
        {
            Program.frmMainWin.ShowTables(0);
        }              

        private void btnDataexchange_Click(object sender, EventArgs e)
        {            
            if (!AppConstVars.LoginState)
            {
                UIMessageBox.Show("用户登录已失效，请重新登录。", "提示：");
                return;
            }
            Program.frmMainWin.ShowTables(1);

            //Task.Factory.StartNew(() =>
            //{
            //    A_SynRmoData();
            //}).TaskDis();
        }

        private void btnGoodsLabel_Click(object sender, EventArgs e)
        {
            var frm = new frmBalance();
            frm.ShowDialog();
            frm.Dispose();
            //if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isSysSetup, 0)) return;
            //var frm = new frmPrintScheme();
            //frm.ShowDialog();
            //frm.Dispose();
        }

        private void btnFoodLablePrin_Click(object sender, EventArgs e)
        {
            var frm = new frmFoodLablePrin();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnFoodWeighing_Click(object sender, EventArgs e)
        {
            var frm = new frmFoodWeighing();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnOrderAbnormal_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isOrderList, 0)) return;
            var frm = new frmOrderList(0, true);
            frm.ShowDialog();
            frm.Dispose();
        }
    }
}